package com.rzjm.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rzjm.api.dao.*;
import com.rzjm.api.entity.*;
import com.rzjm.api.exception.TransactionalException;
import com.rzjm.api.service.DepartmentService;
import com.rzjm.api.service.DeviceWeldingRecordService;
import com.rzjm.api.service.FsrDeviceService;
import com.rzjm.api.service.ShopService;
import com.rzjm.api.util.DateUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class DeviceWeldingRecordServiceImpl extends BaseServiceImpl<DeviceWeldingRecordDao, DeviceWeldingRecord> implements DeviceWeldingRecordService {

    @Resource
    private DeviceWeldingRecordDao weldingRecordDao;
    @Resource
    private DeviceWeldingRecordImgDao deviceRecordImgDao;
    @Resource
    private DeviceWeldingDao deviceWeldingDao;
    @Resource
    private ShopDao shopDao;
    @Resource
    private DepartmentService departmentService;

    @Resource
    private FsrDeviceService fsrDeviceService;

    @Resource
    private FireWorkDao fireWorkDao;

    @Value("${web.imgprefix}")
    private String imgPrefix;

    @Override
    public List<DeviceWeldingRecord> getRecordListByShop(int state,User user, SysUser sysUser, Department departmentSafe,int pageIndex,int pageSize) {
        QueryWrapper<DeviceWeldingRecord> qw = new QueryWrapper<>();
        if(departmentSafe.getDeptType() == 1){
            qw.eq("is_self", 0);

            if(user.getIsTest() == 0) {
                qw.eq("shop_id", departmentSafe.getCompanyId());
//            qw.eq("check_depart_id",departmentSafe.getId());
                qw.eq("depart_check_state", state);
            }
        }else{
//            qw.eq("is_self", 1);
            qw.eq("wx_user_id", user.getId());
            qw.eq("depart_check_state",state);
        }
        qw.orderByDesc("create_time");
        List<DeviceWeldingRecord> list = weldingRecordDao.getPageEntityList(qw,pageIndex,pageSize);
        if(CollUtil.isNotEmpty(list)){
            for (DeviceWeldingRecord weldingRecord : list){

                if(weldingRecord.getManagerSysUserId() != null && weldingRecord.getManagerSysUserId().intValue() == sysUser.getUserId().intValue()){
                    weldingRecord.setIsCanCheck(1);
                }

                List<DeviceWeldingRecordImg> imgList = deviceRecordImgDao.selectListByColumn("record_id", weldingRecord.getId());
                if(CollUtil.isNotEmpty(imgList)){
                    for (DeviceWeldingRecordImg recordImg : imgList){
                        if(StrUtil.isNotEmpty(recordImg.getImgUrl())){
                            recordImg.setImgUrl(imgPrefix + recordImg.getImgUrl());
                        }
                    }
                }
                weldingRecord.setRecordImgs(imgList);
            }
        }
        return list;
    }

    @Override
    @Transactional
    public DeviceWeldingRecord addRecord(int user_id, FsrDevice fsrDevice, SysUser sysUser, DeviceWelding device,int use_state, FireWork fireWork, Shop shop) {
        DeviceWeldingRecord deviceRecord = new DeviceWeldingRecord();
        int ret = 0;
        try{
            if(device.getIsSelf() == 0) {
                device.setUseState(use_state);//申请中
                if(use_state == 1){
                    device.setUseBeginTime(fireWork.getFireBeginTime());
                    device.setUseEndTime(fireWork.getFireEndTime());
                }
            }else{
                if(use_state == 1){
                    device.setUseState(2);//申请中
                    device.setUseBeginTime(fireWork.getFireBeginTime());
                    device.setUseEndTime(fireWork.getFireEndTime());
                }else{
                    device.setUseState(use_state);//申请中
                }
            }
            device.setLastFireWorkId(fireWork.getId());
            ret = deviceWeldingDao.updateById(device);
            if(ret <= 0){
                throw new TransactionalException("deviceWeldingDao updateById error");
            }

            if (use_state == 1) {//申请
                deviceRecord.setWxUserId(user_id);
                deviceRecord.setIsSafe(0);
                deviceRecord.setFireWorkId(fireWork.getId());
                deviceRecord.setDeviceId(device.getId());
                deviceRecord.setDeviceNum(device.getDeviceNo());
                deviceRecord.setDeviceName(device.getDeviceName());
                deviceRecord.setIsSelf(device.getIsSelf());
                deviceRecord.setCreateTime(new Date());
                deviceRecord.setShopId(device.getShopId());
                deviceRecord.setUseAddress(fireWork.getFireAddress());
//                deviceRecord.setDepartCheckState(0);
                deviceRecord.setCheckSysUserId(0L);
                if (device.getIsSelf() == 0) {
                    deviceRecord.setWorkerName(sysUser.getName());
                    deviceRecord.setWorkerPhone(sysUser.getMobile());
                    deviceRecord.setCertificateNum(sysUser.getCertificateNum());
                } else {
                    deviceRecord.setWorkerName(device.getLeaderName());
                    deviceRecord.setWorkerPhone(device.getLeaderPhone());
                    deviceRecord.setCertificateNum(device.getCertificateNum());
                }

                deviceRecord.setUseState(use_state);
                deviceRecord.setUseBeginTime(fireWork.getFireBeginTime());
                deviceRecord.setUseEndTime(fireWork.getFireEndTime());
                if (shop != null) {
                    deviceRecord.setShopName(shop.getShopName());
                }

                deviceRecord.setDepartCheckState(0);
                if (device.getIsSelf() == 0) {//企业焊机
                    deviceRecord.setState(0);
                    if (shop != null) {
                        deviceRecord.setShopName(shop.getShopName());
                        Department departmentSafe = departmentService.getSafeDepart(shop.getId());
                        if (departmentSafe != null) {
                            //安全科部门
                            deviceRecord.setCheckDepartId(departmentSafe.getId());
                        }
                    }
                } else {//自由焊机
                    deviceRecord.setDepartCheckState(1);
                    deviceRecord.setState(1);
                }
            } else {
                QueryWrapper<DeviceWeldingRecord> qw = new QueryWrapper<>();
                qw.eq("fire_work_id", fireWork.getId());
                qw.last("limit 1");
                deviceRecord = weldingRecordDao.selectOne(qw);
                if (deviceRecord != null) {
                    deviceRecord.setRebackTime(new Date());
                    deviceRecord.setState(2);//0 - 新申请  1 - 结束  2 - 归还
                }
            }

            if (use_state == 1) {//新申请
                ret = weldingRecordDao.insert(deviceRecord);
                if(ret <= 0) {
                    throw new TransactionalException("weldingRecordDao insert error");
                }
            } else {
                ret = weldingRecordDao.updateById(deviceRecord);
                if(ret <= 0) {
                    throw new TransactionalException("weldingRecordDao updateById error");
                }
            }

            if(use_state == 1) {//申请使用
                fireWork.setIsUse(1);
                ret = fireWorkDao.updateById(fireWork);
                if(ret <= 0) {
                    throw new TransactionalException("fireWorkDao updateById error");
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            throw new TransactionalException("fireWorkDao system error");
        }
        return deviceRecord;
    }

    @Override
    @Transactional
    public DeviceWeldingRecord addRecordSafe(int user_id, FsrDevice fsrDevice, SysUser sysUser,
                                             DeviceWelding device,  String useAddress, int use_state, Shop shop) {
        DeviceWeldingRecord deviceRecord = new DeviceWeldingRecord();
        int ret = 0;
        try{
            ret = deviceWeldingDao.updateById(device);
            if(ret <= 0) {
                throw new TransactionalException("fireWorkDao updateById error");
            }

            if (device.getIsSelf() == 1) {//自有用户  扫码提交申请的时候，断开和 合闸 是一起执行的 先关后开
                //先开闸
                if (device.getIsHasBreaker() == 1) {
                    fsrDeviceService.commandOp(fsrDevice, 0);
//                    System.out.println("自由焊机，先执行关闭   执行时间： " + DateUtil.getTime());
                }
            }

            if (use_state == 1) {//申请
                deviceRecord.setWxUserId(user_id);
                deviceRecord.setIsSafe(1);
                deviceRecord.setDeviceId(device.getId());
                deviceRecord.setDeviceNum(device.getDeviceNo());
                deviceRecord.setDeviceName(device.getDeviceName());
                deviceRecord.setIsSelf(device.getIsSelf());
                deviceRecord.setCreateTime(new Date());
                deviceRecord.setShopId(device.getShopId());
                deviceRecord.setUseAddress(useAddress);
                deviceRecord.setCheckSysUserId(0L);
                if (device.getIsSelf() == 0) {
                    deviceRecord.setWorkerName(sysUser.getName());
                    deviceRecord.setWorkerPhone(sysUser.getMobile());
                    deviceRecord.setCertificateNum(sysUser.getCertificateNum());
                } else {
                    deviceRecord.setWorkerName(device.getLeaderName());
                    deviceRecord.setWorkerPhone(device.getLeaderPhone());
                    deviceRecord.setCertificateNum(device.getCertificateNum());
                }
                deviceRecord.setManagerCheckState(0);
                deviceRecord.setUseState(use_state);
                deviceRecord.setUseBeginTime(device.getUseBeginTime());
                deviceRecord.setUseEndTime(device.getUseEndTime());
                deviceRecord.setDepartCheckState(0);
                if (device.getIsSelf() == 0) {
                    deviceRecord.setState(1);
                    if (shop != null) {
                        deviceRecord.setShopName(shop.getShopName());
                        deviceRecord.setManagerSysUserId(shop.getFireChargeSysUserId());
                        Department departmentSafe = departmentService.getSafeDepart(shop.getId());
                        if (departmentSafe != null) {
                            //安全科部门
                            deviceRecord.setCheckDepartId(departmentSafe.getId());
                        }
                    }
                } else {
                    //0 - 待审核 1 - 审核通过 2 - 审核驳回
                    deviceRecord.setDepartCheckState(1);
                    deviceRecord.setState(1);
                }
            } else {
                QueryWrapper<DeviceWeldingRecord> qw = new QueryWrapper<>();
                qw.eq("device_id", device.getId());
                qw.eq("state", 1);
                qw.last("limit 1");
                qw.orderByDesc("id");
                deviceRecord = weldingRecordDao.selectOne(qw);
                if (deviceRecord != null) {
                    deviceRecord.setRebackTime(new Date());
                    deviceRecord.setState(2);//0 - 新申请  1 - 结束  2 - 归还
                }
            }

            if (use_state == 1) {//新申请
                ret = weldingRecordDao.insert(deviceRecord);
                if(ret <= 0) {
                    throw new TransactionalException("weldingRecordDao insert error");
                }
            } else {
                ret = weldingRecordDao.updateById(deviceRecord);
                if(ret <= 0) {
                    throw new TransactionalException("weldingRecordDao updateById error");
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            throw new TransactionalException("fireWorkDao system error");
        }
        return deviceRecord;
    }

    @Override
    @Transactional
    public int managerCheckRecord(DeviceWeldingRecord deviceRecord, SysUser sysUser, DeviceWelding device,int check_state,String check_result) {
        int ret = 0;
        try{

            /**
             * 0 - 待审核 1 - 审核通过 2 - 审核驳回
             */
//            deviceRecord.setManagerSysUserId(sysUser.getUserId());
            deviceRecord.setManagerCheckState(check_state);
            deviceRecord.setManagerCheckResult(check_result);
            deviceRecord.setManagerCheckTime(new Date());
            if(check_state == 2){//审核驳回
                device.setUseState(0);
                ret = deviceWeldingDao.updateById(device);
                if(ret <= 0) {
                    throw new TransactionalException("deviceWeldingDao updateById error");
                }
            }else if(check_state == 1){
                //使用状态 0 - 未使用  1 - 申请中 2 - 审核通过使用中
                device.setUseState(2);
                //企业申请  通过后  修改 使用时间
                if(deviceRecord.getIsSelf() == 0){
                    device.setUseBeginTime(deviceRecord.getUseBeginTime());
                    device.setUseEndTime(deviceRecord.getUseEndTime());
                }
                ret = deviceWeldingDao.updateById(device);
                if(ret <= 0) {
                    throw new TransactionalException("deviceWeldingDao updateById error");
                }
            }

            ret = weldingRecordDao.updateById(deviceRecord);
            if(ret <= 0) {
                throw new TransactionalException("weldingRecordDao updateById error");
            }

        }catch (Exception e){
            e.printStackTrace();
            throw new TransactionalException("managerCheckRecord system error");
        }
        return ret;
    }
}
